// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package menu

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"context"
	"encoding/json"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuOptionsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuOptionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuOptionsLogic {
	return &MenuOptionsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuOptionsLogic) MenuOptions() (resp []types.MenuOptions, err error) {
	menuModel := model.NewMenuModel(l.svcCtx.Conn)
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	menuList, err := menuModel.FindUserMenuOptions(l.ctx, userId)
	var result []types.MenuOptions
	for _, menu := range menuList {
		result = append(result, types.MenuOptions{
			MenuId:   int(menu.Id),
			ParentId: sqlutil.NullInt64ToInt(menu.ParentId),
			Title:    sqlutil.NullStringToString(menu.Title),
		})
	}
	tree2 := buildMenuTree2(result, 0)
	return tree2, nil
}

func buildMenuTree2(menus []types.MenuOptions, parentId int64) []types.MenuOptions {
	var rootMenus []types.MenuOptions
	for _, menu := range menus {
		if menu.ParentId == parentId {
			menu.Children = buildMenuTree2(menus, int64(menu.MenuId))
			rootMenus = append(rootMenus, menu)
		}
	}
	return rootMenus
}
